package mspbots.autotask.data.core.contractrolecosts;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Log4j2
@Component
@RequiredArgsConstructor
public class ContractRoleCostsReceiver {

    private final ContractRoleCostsRepository contractRoleCostsRepository;

//    @RabbitListener(queues = "auto-task.contract-role-costs.sync")
    public void syncTask(ResultMsg content) {
        ContractRoleCosts contractRoleCosts = ContractRoleCosts.builder().otherId(content.getId())
                .tenantId(content.getTenantId()).syncTime(content.getSyncDate())
                .entity(content.getEntity())
                .build();

        this.contractRoleCostsRepository.findByOtherIdAndTenantId(content.getId(), content.getTenantId())
                .map(ticket -> {
                    contractRoleCosts.setId(ticket.getId());
                    return contractRoleCosts;

                })
                .defaultIfEmpty(contractRoleCosts)
                .flatMap(this.contractRoleCostsRepository::save)
                .block(Duration.ofSeconds(10));
    }
}
